package services

import (
	"context"
	"fmt"
	"gateway-server/internal/logger"
	"gateway-server/internal/registry"
	"time"
)

type Service struct {
	Registry *registry.EtcdRegistry
	Name     string
	Address  string
}

type ServiceRegister struct {
	Services   []Service
	MaxRetries int
}

func (s *Service) StartRegistration(ctx context.Context, sr *ServiceRegister) (context.CancelFunc, error) {
	if s.Registry == nil {
		return nil, fmt.Errorf("registry is not initialized for service: %s", s.Name)
	}

	ctx, cancel := context.WithCancel(ctx)
	ticker := time.NewTicker(time.Second * 8)
	go func() {
		defer ticker.Stop()
		retryCount := 0
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				maxRetries := sr.MaxRetries
				err := s.Registry.RegisterService(s.Name, s.Address)
				if err != nil {
					logger.Default.Infof("register service error: %v", err)
					retryCount++
					if retryCount >= maxRetries && maxRetries > 0 {
						logger.Default.Errorf("maximum retry attempts (%d) reached for service: %s", maxRetries, s.Name)
						cancel()
						return
					}
				} else {
					retryCount = 0
				}
			}
		}
	}()
	return cancel, nil

}

func (sr *ServiceRegister) StartAllRegistrations(parentCtx context.Context) ([]context.CancelFunc, error) {
	var cancelFuncList []context.CancelFunc
	for _, svc := range sr.Services {
		cancel, err := svc.StartRegistration(parentCtx, sr)
		if err != nil {
			return nil, err
		}
		cancelFuncList = append(cancelFuncList, cancel)
	}
	return cancelFuncList, nil
}
